package cn.lls.controller.employee;

import cn.lls.base.result.R;
import cn.lls.base.result.ResultCode;
import cn.lls.excel.EmployeeExcel;
import cn.lls.req.emp.ConditionSearchEmployeeExcelReq;
import cn.lls.req.emp.ConditionSearchEmployeeReq;
import cn.lls.req.emp.EmployeeInfoReq;
import cn.lls.service.ICompanyBaseService;
import cn.lls.service.IEmployeeService;
import cn.lls.vo.emp.EmployeeInfo;
import cn.lls.vo.emp.EmployeeInfoVO;
import com.alibaba.excel.EasyExcel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 员工信息控制器
 *
 * @ClassName EmployeeController
 * @Author 划水艺术家
 * @Date 2022/11/21 23:11
 * @Version 1.0
 **/
@RestController
@RequestMapping("/emp/ope")
@Slf4j
@Api(tags = "员工信息操作控制器")
public class EmployeeOpeController {

    @Autowired
    private IEmployeeService employeeService;

    @Autowired
    private ICompanyBaseService companyBaseService;

    @PostMapping
    @ApiOperation(value = "添加员工信息", notes = "添加员工信息", response = R.class, httpMethod = "POST")
    public R addEmployee(@RequestBody @Validated EmployeeInfoReq employeeInfoReq,
                         BindingResult bindingResult){
        employeeService.addEmployee(employeeInfoReq);
        return R.success();
    }

    @PutMapping
    @ApiOperation(value = "更改员工信息", notes = "更改员工信息", response = R.class, httpMethod = "PUT")
    public R updateEmployee(@RequestBody @Validated EmployeeInfoReq employeeInfoReq,
                         BindingResult bindingResult){
//        log.info("employeeReq = {}", employeeInfoReq);
        employeeService.updateEmployee(employeeInfoReq);
        return R.success();
    }

    @DeleteMapping("/{employeeId}")
    @ApiOperation(value = "删除员工信息", notes = "删除员工信息", response = R.class, httpMethod = "DELETE")
    public R delEmployee(@PathVariable("employeeId") @NotNull(message = "必须指定员工Id") Long employeeId,
                         BindingResult bindingResult){
        try {
            if (companyBaseService.removeById(employeeId))
                return R.success();
        } catch (Exception e) {
            return R.fail(ResultCode.DATABASE_ERROR, "员工删除失败");
        }
        return R.fail(ResultCode.DATABASE_ERROR, "员工删除失败");
    }

    @PostMapping("/info")
    @ApiOperation(value = "分页条件查询员工信息", notes = "分页条件查询员工信息", response = R.class, httpMethod = "POST")
    public R getEmployeeByConditionAndPage(@RequestBody @Validated ConditionSearchEmployeeReq conditionSearchEmployeeReq,
                            BindingResult bindingResult){
        try {
            EmployeeInfoVO employeeInfoVO = new EmployeeInfoVO();
            BeanUtils.copyProperties(employeeService.getEmployeeByConditionAndPage(conditionSearchEmployeeReq),
                    employeeInfoVO);
//            log.info("employeeInfoVO = {}", employeeInfoVO);
            return R.success(employeeInfoVO);
        } catch (Exception e){
            e.printStackTrace();
            return R.fail(ResultCode.DATABASE_ERROR, "查询数据失败");
        }
    }


    @GetMapping("/{employeeId}")
    @ApiOperation(value = "根据Id查询员工详情信息", notes = "根据Id查询员工详情信息", response = R.class, httpMethod = "GET")
    public R getEmployeeById(@PathVariable("employeeId") @NotNull(message = "必须指定员工Id") Long employeeId){
        return R.success(employeeService.getEmployeeById(employeeId));
    }

    @PostMapping("/info/export")
    @ApiOperation(value = "导出员工信息到excel", notes = "导出员工信息到excel", response = R.class, httpMethod = "POST", produces = "application/octet-stream")
    public void exportEmployeeInfo(@RequestBody @Validated ConditionSearchEmployeeExcelReq conditionSearchEmployeeExcelReq,
                                           BindingResult bindingResult, HttpServletResponse response) throws IOException {
        try {
            // 设置文本内省
            response.setContentType("application/vnd.ms-excel");
            // 设置字符编码
            response.setCharacterEncoding("utf-8");
            // 设置响应头
            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition, lls-code");
            response.setHeader("Content-disposition", "attachment;filename=employeeInfo.xlsx");
            response.setHeader("lls-code", "200");
            List<EmployeeInfo> employeeInfos = employeeService.getEmployeeExcel(conditionSearchEmployeeExcelReq);
//            String fileName = "F://1.xlsx";
//            EasyExcel.write(fileName, EmployeeExcel.class).sheet(0).includeColumnFiledNames(conditionSearchEmployeeExcelReq.getFields()).doWrite(employeeExcel);
            List<EmployeeExcel> employeeExcels = employeeInfos.stream().map(employeeInfo -> {
                EmployeeExcel e = new EmployeeExcel();
                BeanUtils.copyProperties(employeeInfo, e);
                try {
                    e.setEmployeeImage(new URL(employeeInfo.getEmployeeImage()));
                } catch (MalformedURLException ex) {
                    ex.printStackTrace();
                }
                return e;
            }).collect(Collectors.toList());
//            log.info("employeeExcels = {}", employeeExcels);
            EasyExcel.write(response.getOutputStream(), EmployeeExcel.class)
                    .sheet("员工信息")
                    .includeColumnFiledNames(conditionSearchEmployeeExcelReq.getFields())
                    .doWrite(employeeExcels);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
